package com.lrm.dao;

import com.lrm.po.Blog;
import com.lrm.po.Type;
import com.lrm.po.User;
import com.lrm.util.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class UserController {
    public static User findOne(Long id){
        User user = null;
        try{
            Connection con = DBUtils.getConnection();
            String sql = "select * from t_user where id = ?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setObject(1, id);
            ResultSet result = ps.executeQuery();
            int i = 0;
            while(result.next()){
                if(i < 1){
                    user = new User();
                    user.setPassword(result.getString("password"));
                    user.setId(result.getLong("id"));
                    user.setAvatar(result.getString("avatar"));
                    user.setCreateTime(result.getDate("create_time"));
                    user.setEmail(result.getString("email"));
                    user.setNickname(result.getString("nickname"));
                    user.setType(result.getInt("type"));
                    user.setUpdateTime(result.getDate("update_time"));
                    user.setUsername(result.getString("username"));
                }
                else{
                    break;
                }
            }
        }
        catch (Exception e){
            throw new RuntimeException(e);
        }
        return user;
    }

    public static User findByUsernameAndPassword(String username, String password){
        User user = null;
        try{
            Connection con = DBUtils.getConnection();
            String sql = "select * from t_user where username = ? and password = ?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setObject(1, username);
            ps.setObject(2, password);
            ResultSet result = ps.executeQuery();
            int i = 0;
            while(result.next()){
                if(i < 1){
                    user = new User();
                    user.setPassword(result.getString("password"));
                    user.setId(result.getLong("id"));
                    user.setAvatar(result.getString("avatar"));
                    user.setCreateTime(result.getDate("create_time"));
                    user.setEmail(result.getString("email"));
                    user.setNickname(result.getString("nickname"));
                    user.setType(result.getInt("type"));
                    user.setUpdateTime(result.getDate("update_time"));
                    user.setUsername(result.getString("username"));
                }
                else{
                    break;
                }
            }
        }
        catch (Exception e){
            throw new RuntimeException(e);
        }
        return user;
    }
}
